package exporter

import (
	"emc_vnx_exporter/utils"
	"github.com/prometheus/client_golang/prometheus"
	"io/ioutil"
	"log"
	"os/exec"
	"strings"
	"time"
)

type Host struct {
	Name                    string
	PackageRevision         string
	CommitRequired          string
	RevertPossible          string
	ActiveState             string
	IsInstallationCompleted string
	IsSystemSoftware        string
}

var (
	host = prometheus.NewGaugeVec(
		prometheus.GaugeOpts{
			Name: "vnx_get_all_host",
			Help: "Get All Host Info",
		},
		[]string{"name", "PackageRevision", "CommitRequired", "RevertPossible", "ActiveState", "IsInstallationCompleted", "IsSystemSoftware"},
	)
)

func HostGauge() *prometheus.GaugeVec {
	return host
}

func GetAllHostMetrics(spIp string, user string, password string) {
	for {
		cmd := exec.Command("bash", "-c", "/opt/Navisphere/bin/naviseccli -h "+spIp+" -user "+user+" -password "+password+" -Scope 0 getall -host | tail -n +29")
		stdout, _ := cmd.StdoutPipe()
		defer stdout.Close()
		if err := cmd.Start(); err != nil {
			log.Fatalf("cmd.Start: %v", err)
		}
		result, _ := ioutil.ReadAll(stdout) // 读取输出结果
		resData := string(result)

		hostList := strings.Split(resData, "\n\n")
		for _, hostString := range hostList {
			hostItems := strings.Split(hostString, "\n")
			data := new(Host)
			for _, hostItem := range hostItems {
				if hostItem == "" {
					continue
				}
				value := hostItem[strings.Index(hostItem, ":")+1 : strings.Count(hostItem, "")-1]
				value = strings.Replace(value, "  ", "", -1)
				if strings.Contains(hostItem, "Name of the software package") {
					data.Name = value
				} else if strings.Contains(hostItem, "Revision of the software package") {
					data.PackageRevision = value
				} else if strings.Contains(hostItem, "Commit Required") {
					data.CommitRequired = value
				} else if strings.Contains(hostItem, "Revert Possible") {
					data.RevertPossible = value
				} else if strings.Contains(hostItem, "Active State") {
					data.ActiveState = value
				} else if strings.Contains(hostItem, "Is installation completed") {
					data.IsInstallationCompleted = value
				} else if strings.Contains(hostItem, "Is this System Software") {
					data.IsSystemSoftware = value
				}
			}
			if data.Name != "" {
				host.WithLabelValues(data.Name, data.PackageRevision, data.CommitRequired, data.RevertPossible, data.ActiveState, data.IsInstallationCompleted, data.IsSystemSoftware).Set(utils.HostActiveStateToFloat(data.ActiveState))
			}
		}

		time.Sleep(60 * time.Second)
	}
}
